<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="销售订单编码" prop="sordId">
        <el-input
          v-model="queryParams.sordId"
          placeholder="请输入销售订单编码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="订单名" prop="sordName">
        <el-input
          v-model="queryParams.sordName"
          placeholder="请输入订单名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
<!--      <el-form-item label="产品编码" prop="prodId">-->
<!--        <el-input-->
<!--          v-model="queryParams.prodId"-->
<!--          placeholder="请输入产品编码"-->
<!--          clearable-->
<!--          @keyup.enter.native="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
<!--      <el-form-item label="产品数量" prop="prodNum">-->
<!--        <el-input-->
<!--          v-model="queryParams.prodNum"-->
<!--          placeholder="请输入产品数量"-->
<!--          clearable-->
<!--          @keyup.enter.native="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->

      <el-form-item label="下单日期" prop="sordStartTime">
        <el-date-picker clearable
          v-model="queryParams.sordStartTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择下单日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="交货日期" prop="sordFinTime">
        <el-date-picker clearable
          v-model="queryParams.sordFinTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择交货日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="订单状态" prop="sordStatus">
        <el-select v-model="queryParams.sordStatus" placeholder="请选择订单状态" clearable>
          <el-option
            v-for="dict in dict.type.sord_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="客户编号" prop="clientId">
        <el-input
          v-model="queryParams.clientId"
          placeholder="请输入客户编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:sord:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:sord:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:sord:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:sord:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="sordList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="销售订单id" align="center" prop="id" />
      <el-table-column label="销售订单编码" align="center" prop="sordId" />
      <el-table-column label="订单名" align="center" prop="sordName" />
<!--      <el-table-column label="产品编码" align="center" prop="prodId" />-->
<!--      <el-table-column label="产品数量" align="center" prop="prodNum" />-->
      <el-table-column label="下单日期" align="center" prop="sordStartTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.sordStartTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="交货日期" align="center" prop="sordFinTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.sordFinTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="订单状态" align="center" prop="sordStatus">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sord_status" :value="scope.row.sordStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="客户编号" align="center" prop="clientId" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="HandleExamine(scope.row)"
          >查看</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:sord:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:sord:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改销售订单对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="700px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="销售订单编码" prop="sordId">
          <el-input v-model="form.sordId" placeholder="请输入销售订单编码" :readonly="!isVisible"/>
        </el-form-item>
        <el-form-item label="订单名" prop="sordName">
          <el-input v-model="form.sordName" placeholder="请输入订单名" :readonly="!isVisible"/>
        </el-form-item>
<!--        <el-form-item label="产品编码" prop="prodId" >-->
<!--          <el-select v-model="form.prodId" filterable placeholder="请选择">-->
<!--            <el-option v-for="item in productinfoselectoption" :key="item.id" :label="item.prodId" :value="item.prodId">-->
<!--            </el-option>-->
<!--          </el-select>-->
<!--        </el-form-item>-->
<!--        <el-form-item label="产品数量" prop="prodNum">-->
<!--          <el-input v-model="form.prodNum" placeholder="请输入产品数量" />-->
<!--        </el-form-item>-->
        <el-form-item label="下单日期" prop="sordStartTime">
          <el-date-picker clearable
            v-model="form.sordStartTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择下单日期" :readonly="!isVisible">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="交货日期" prop="sordFinTime">
          <el-date-picker clearable
            v-model="form.sordFinTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择交货日期" :readonly="!isVisible">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="订单状态" prop="sordStatus">
          <el-select v-model="form.sordStatus" placeholder="请选择订单状态" :disabled="!isVisible">
            <el-option
              v-for="dict in dict.type.sord_status"
              :key="dict.value"
              :label="dict.label"
:value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="客户编码" prop="clientId" >
          <el-select v-model="form.clientId" filterable placeholder="请选择" :disabled="!isVisible">
            <el-option v-for="item in clientinfoselectoption" :key="item.id" :label="item.clientId" :value="item.clientId" >
            </el-option>
          </el-select>
        </el-form-item>
        <el-divider>产 品 列 表</el-divider>
        <el-button v-if="isVisible" style="margin-bottom: 10px;" type="primary" @click="processadd">添 加</el-button>
        <el-card shadow="always" style="border-radius: 15px;">
          <el-table style="border-radius: 15px;" v-loading="loading" border :data="form.mtrs">
            <el-table-column label="产品" align="" prop="mtrName" align="center">
              <template slot-scope="scope" >
                <el-select v-model="scope.row.prodId" filterable placeholder="请选择"
                           @change="(option) => mtrchang(option, scope.$index)" :disabled="!isVisible">

                  <el-option v-for="item in productinfoselectoption" :key="item.prodId" :label="item.prodId" :value="item.prodId">
                  </el-option>
                </el-select>
              </template>
            </el-table-column>

            <el-table-column label="数量" align="center"  width="230px">
              <template slot-scope="scope">
                <el-input-number id="inputNumber" v-model:value="scope.row.prodNum" :min="0" :precision="0" :disabled="!isVisible"/>
              </template>
            </el-table-column>

            <el-table-column label="操作" align="center" class-name="small-padding fixed-width" v-if="isVisible">
              <template slot-scope="scope">
                <el-button size="mini" type="text" icon="el-icon-edit" @click="processadd(scope.$index, scope.row)"
                           v-hasPermi="['mes:proinfo:edit']">增加</el-button>
                <el-button size="mini" type="text" icon="el-icon-delete" @click="processdel(scope.$index)"
                           v-hasPermi="['mes:proinfo:remove']">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>


      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" v-if="isVisible">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listSord, getSord, delSord, addSord, updateSord } from "@/api/system/sord";
import {listInspection} from "@/api/system/inspection";
import {listProduct} from "@/api/system/product";
import {listClient} from "@/api/system/client";
import {addBom, getBom, updateBom} from "@/api/system/bom";
import {addMatbom, fetchMatIdsByBomId, updateMatbom} from "@/api/system/matbom";
import {addProd, fetchProdIdsBySordId, updateProd} from "@/api/system/prod";

export default {
  name: "Sord",
  dicts: ['sord_status'],
  data() {
    return {
      isVisible : false,

      //产品下拉框数据
      productinfoselectoption: [],
      //客户下拉框数据
      clientinfoselectoption: [],
      //销售订单拥有的产品
      sordprod:[],

      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 销售订单表格数据
      sordList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        sordId: null,
        // oldSordId: null,
        sordName: null,
        // prodId: null,
        // prodNum: null,
        sordStartTime: null,
        sordFinTime: null,
        sordStatus: null,
        clientId: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        sordId: [
          { required: true, message: "销售订单编码不能为空", trigger: "blur" }
        ],
        sordName: [
          { required: true, message: "订单名不能为空", trigger: "blur" }
        ],
        prodId: [
          { required: true, message: "产品编码不能为空", trigger: "blur" }
        ],
        prodNum: [
          { required: true, message: "产品数量不能为空", trigger: "blur" }
        ],
        sordStartTime: [
          { required: true, message: "下单日期不能为空", trigger: "blur" }
        ],
        sordFinTime: [
          { required: true, message: "交货日期不能为空", trigger: "blur" }
        ],
        sordStatus: [
          { required: true, message: "订单状态不能为空", trigger: "change" }
        ],
        clientId: [
          { required: true, message: "客户编号不能为空", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    mtrchang(option, index) {
      let ss = this.productinfoselectoption.find(item => item.prodId == option)
      if(ss) {
        this.form.mtrs[index].id = ss.id
        this.form.mtrs[index].sordId = this.form.sordId//销售订单编码
        this.form.mtrs[index].prodId = ss.prodId// 产品编码
        this.form.mtrs[index].prodNum = this.form.prodNum //产品数量
      }
    },

    processdel(index) {
      this.form.mtrs.splice(index, 1)
    },

    processadd(index, row) {
      if (index != undefined) {
        this.form.mtrs.splice(index + 1, 0,
          {
            id:null,
            sordId:null,
            prodId:null,
            prodNum: 0
          }
        )
      } else {
        this.form.mtrs.push(
          {
            id:null,
            sordId:null,
            prodId:null,
            prodNum: 0
          }
        )
      }
    },

    /** 查询销售订单列表 */
    getList() {
      this.loading = true;
      listSord(this.queryParams).then(response => {
        this.sordList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
      //产品列表
      listProduct().then((res) => {
        this.productinfoselectoption = res.rows
        console.log("🚀 ~ file: index.vue:240 ~ listProinfo ~ this.productinfoselectoption:", this.productinfoselectoption)
      });
      //客户列表
      listClient().then((res) => {
        this.clientinfoselectoption = res.rows
        console.log("🚀 ~ file: index.vue:240 ~ listProinfo ~ this.productinfoselectoption:", this.clientinfoselectoption)
      })
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.isVisible = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        sordId: null,
        sordName: null,
        // prodId: null,
        // prodNum: null,
        sordStartTime: null,
        sordFinTime: null,
        sordStatus: null,
        clientId: null,
        oldSordId:null,
        mtrs:[],
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /**
     * 查看按钮操作 */
    HandleExamine(row) {
      this.reset();
      this.isVisible = false;
      const id = row.id || this.ids
      getSord(id).then(response => {
        this.form = response.data;

        this.form.oldSordId = this.form.sordId;

        //根据bomId去查看bom包含的所有原料
        fetchProdIdsBySordId(this.form.sordId).then((res) =>{
          this.sordprod = res.data;
          this.form.mtrs = this.sordprod

          this.open = true;
          this.title = "查看销售订单";
        });
      });
    },



    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.isVisible = true;
      this.open = true;
      this.title = "添加销售订单";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.isVisible = true;
      const id = row.id || this.ids
      getSord(id).then(response => {
        this.form = response.data;
        this.form.oldSordId = this.form.sordId;

          //根据sordId去查看销售订单包含的所有产品
          fetchProdIdsBySordId(this.form.sordId).then((res) =>{
            this.sordprod = res.data;
            this.form.mtrs = this.sordprod

        this.open = true;
        this.title = "修改销售订单";
        });
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {

          if (this.form.mtrs.findIndex(e => { return e.id == null }) != -1 || this.form.mtrs.length == 0) {
            this.$modal.msgError("请添加或将产品信息填写完整");
          } else {
            const hasEmptyNum = this.form.mtrs.some(item => item.prodNum === null || item.prodNum === undefined || isNaN(item.prodNum) || item.prodNum === 0 );
            let matIdMap = {};
            let isMatIdUnique = true;
            for (let i = 0; i < this.form.mtrs.length; i++) {
              let currentMatId = this.form.mtrs[i].prodId;
              if (matIdMap[currentMatId]) {
                isMatIdUnique = false;
                break;
              } else {
                matIdMap[currentMatId] = true;
              }
            }

            if (hasEmptyNum) {
              this.$message.warning('请检查所有产品的数量，确保已填写！');
            }else {
              if(isMatIdUnique){

                if (this.form.id != null) {

                  this.form.mtrs.forEach(item => {
                    item.sordId = this.form.sordId;
                    item.oldSordId = this.form.oldSordId;
                  });

                  updateSord(this.form).then(response => {
                    this.$modal.msgSuccess("修改销售订单成功");
                    this.open = false;
                    this.getList();
                    return updateProd(this.form);
                  })
                    .then(response => {
                      this.$modal.msgSuccess("修改bom原料成功");
                    })
                    .catch(error => {
                      if (error && (error.message === "销售订单编号重复" || (error.response && error.response.data && error.response.data.message === "销售订单编号重复"))) {
                        this.$modal.msgError("修改销售订单失败，销售订单编码重复");
                        this.reset();
                      } else {
                        console.error("发生错误:", error);
                        this.$modal.msgError("修改销售订单或销售订单产品时发生错误");
                      }
                    });

                } else {

                  addSord(this.form)
                    .then(response => {
                      this.$modal.msgSuccess("新增销售订单成功");
                      this.open = false;
                      this.getList();
                      return addProd(this.form);
                    })
                    .then(response => {

                      this.$modal.msgSuccess("新增销售订单产品成功");
                    })
                    .catch(error => {
                      if (error && (error.message === "销售订单编号重复" || (error.response && error.response.data && error.response.data.message === "销售订单编号重复"))) {
                        this.$modal.msgError("新增销售订单失败，销售订单编码重复");
                        this.reset();
                      } else {
                        console.error("发生错误:", error);
                        this.$modal.msgError("新增销售订单时发生错误");
                      }
                    });
                }
              }else {
                this.$message.warning('产品不能重复！');
              }
            }
          }


        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除销售订单编号为"' + ids + '"的数据项？').then(function() {
        return delSord(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/sord/export', {
        ...this.queryParams
      }, `sord_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
